package com.youlu.campus.service.activity;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.req.CaCollectReq;
import com.youlu.campus.entity.VO.req.PointPlaceOrderVO;
import com.youlu.campus.entity.VO.req.UserCaQuery;
import com.youlu.campus.entity.VO.res.ActivityDetailResponse;
import com.youlu.campus.entity.VO.res.MyBadgeRuleResponse;
import com.youlu.campus.entity.VO.res.UserActivityHomePageResponse;
import com.youlu.campus.entity.ca.GiftCaInfo;
import com.youlu.campus.entity.domain.CsInfoDomain;
import com.youlu.campus.entity.domain.UserCaDomain;
import com.youlu.campus.entity.english.UserCompetitionQa;
import com.youlu.campus.entity.english.vo.response.CompetitionUserInviteResponse;
import com.youlu.campus.entity.enums.CaMaterialType;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.service.activity.impl.ActivityPayConfigService;
import com.youlu.campus.service.base.BaseService;
import com.youlu.campus.service.ca.CaInfoService;
import com.youlu.campus.service.ca.UserCaReceiveRecordService;
import com.youlu.campus.service.ca.impl.CaCollectService;
import com.youlu.campus.service.ca.impl.CertificateActivityConfigService;
import com.youlu.campus.service.cache.CacheActivityService;
import com.youlu.campus.service.english.CompetitionUserInviteService;
import com.youlu.campus.service.invite.UserInviteRecordService;
import com.youlu.campus.service.item.ItemInfoService;
import com.youlu.campus.service.platform.PlatformConfigService;
import com.youlu.campus.service.platform.PointPlatformConfigService;
import com.youlu.campus.service.postage.PostageTemplateService;
import com.youlu.campus.service.qa.ActivityQaInfoService;
import com.youlu.campus.service.ranking.UserActivityPointDetailService;
import com.youlu.campus.service.ranking.UserActivityPointRankingService;
import com.youlu.campus.service.ranking.entity.UserActivityPointRanking;
import com.youlu.campus.service.visitor.UserAddressInfoService;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import com.youlu.campus.service.visitor.UserPointsService;
import com.youlu.campus.service.wechat.SystemNickNameAndHeaderImageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class QQMiniActivityService extends BaseService {

    @Autowired
    private ActivityPlatformConfigService activityPlatformConfigService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ActivityQaInfoService activityQaInfoService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private SystemNickNameAndHeaderImageService systemNickNameAndHeaderImageService;

    @Autowired
    private UserInfoExtendService userInfoExtendService;

    @Autowired
    private ActivityTaskService activityTaskService;

    @Autowired
    private UserActivityPointRankingService userActivityPointRankingService;

    @Autowired
    private CompetitionUserInviteService competitionUserInviteService;

    @Autowired
    private ItemInfoService itemInfoService;

    @Autowired
    private PlatformConfigService platformConfigService;
    @Autowired
    private UserAddressInfoService userAddressInfoService;

    @Autowired
    private UserPointsService userPointsService;
    @Autowired
    private ActivityPayConfigService activityPayConfigService;
    @Autowired
    private CacheActivityService cacheActivityService;
    @Autowired
    private PostageTemplateService postageTemplateService;
    @Autowired
    private UserCaReceiveRecordService userCaReceiveRecordService;
    @Autowired
    private CaInfoService caInfoService;

    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;
    @Autowired
    private ActivityPointConfigService activityPointConfigService;
    @Autowired
    private UserActivityPointDetailService userActivityPointDetailService;

    @Autowired
    private PointPlatformConfigService pointPlatformConfigService;

    @Autowired
    private CaCollectService caCollectService;


    @Autowired
    private CertificateActivityConfigService certificateActivityConfigService;

    @Autowired
    private UserInviteRecordService userInviteRecordService;

    /**
     * 活动主页
     *
     * @param currentUser
     * @param activityId
     * @return
     */
    public UserActivityHomePageResponse pageHome(UserPO currentUser, String appId, String activityId) {
        ActivityInfo activityInfo = activityService.findOne(activityId);
        if (Objects.isNull(activityInfo)) {
            throw new BusinessException("该活动不存在");
        }

        //活动结束时间
        Date endTime = activityInfo.getEndTime();
        UserActivityHomePageResponse userActivityHomePage = new UserActivityHomePageResponse();
        userActivityHomePage.setBackGroundImageUrl(activityInfo.getHeaderImageUrl());
        userActivityHomePage.setHeaderImageUrl2(activityInfo.getHeaderImageUrl2());
        userActivityHomePage.setDetail(activityInfo.getDetail());
        userActivityHomePage.setRewardsDetail(activityInfo.getRewardsDetail());
        userActivityHomePage.setHonorButtonImgUrl(activityInfo.getHonorButtonImgUrl());
        userActivityHomePage.setCultureCreateButtonImgUrl(activityInfo.getCultureCreateButtonImgUrl());
        userActivityHomePage.setRankingButtonImgUrl(activityInfo.getRankingButtonImgUrl());
        userActivityHomePage.setHeaderHeight(activityInfo.getHeaderHeight());
        userActivityHomePage.setRewardsImage(activityInfo.getRewardsImage());
        userActivityHomePage.setDetailImage(activityInfo.getDetailImage());
        userActivityHomePage.setRewardValueImgUrl(activityInfo.getRewardValueImgUrl());
        userActivityHomePage.setThemeColor(activityInfo.getThemeColor());
        List<CsInfoDomain> csInfoList = activityInfo.getCsInfos();
        //获取客服信息
        if (CollectionUtils.isNotEmpty(csInfoList)) {
            Optional<CsInfoDomain> qqOptional =
                    csInfoList.stream().filter(csInfoDomain -> "QQ".equals(csInfoDomain.getType())).findFirst();
            if (qqOptional.isPresent()) {
                if (StringUtils.isNotBlank(qqOptional.get().getNumber())) {
                    userActivityHomePage.setQqGroupList(qqOptional.get().getNumber().split(","));
                }
                userActivityHomePage.setCsQQGroupImageUrl(qqOptional.get().getImageUrl());
            }
        }
        //QQ客服支持
        userActivityHomePage.setCsList(pointPlatformConfigService.findCsByAppIdAndPlatform(appId, "qq"));
        Date now = new Date();
        if (endTime.after(now)) {//活动时间大于当前时间
            userActivityHomePage.setStatus(2);
        } else if (endTime.before(now)) {//活动时间小于当前时间
            userActivityHomePage.setStatus(3);
        } else {//未开始情况
            userActivityHomePage.setStatus(1);
        }
        //获取用户头像、昵称信息
        if (Objects.isNull(currentUser)) {
            SystemNickNameAndHeaderImage randomHeaderImage = systemNickNameAndHeaderImageService.getRandom();
            if (Objects.nonNull(randomHeaderImage)) {
                userActivityHomePage.setAvatarUrl(randomHeaderImage.getAvatarUrl());
            }
        } else {
            if (StringUtils.isBlank(currentUser.getAvatarUrl())) {
                SystemNickNameAndHeaderImage randomHeaderImage = systemNickNameAndHeaderImageService.getRandom();
                if (Objects.nonNull(randomHeaderImage)) {
                    userActivityHomePage.setAvatarUrl(randomHeaderImage.getAvatarUrl());
                }
            } else {
                userActivityHomePage.setAvatarUrl(currentUser.getAvatarUrl());
                userActivityHomePage.setNickName(currentUser.getNickName());
            }
            //判断用户是否有报名
            UserInfoExtend userInfoExtend = userInfoExtendService.findByUserIdAndAppId(currentUser);
            if (Objects.nonNull(userInfoExtend)) {
                userActivityHomePage.setJoined(Boolean.TRUE);
                UserParticipateActivityInfo userParticipateActivityInfo =
                        userParticipateActivityInfoService.findByUserIdActivityId(currentUser.getId(), activityId);
                if (Objects.nonNull(userParticipateActivityInfo)) {
                    userActivityHomePage.setJoinActivity(Boolean.TRUE);
                }
            }

        }
        //获取任务信息
        ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.INVITE);
        if (Objects.nonNull(activityTaskInfo)) {
            userActivityHomePage.setInviteValue(activityTaskInfo.getRatio().intValue());
            userActivityHomePage.setTaskId(activityTaskInfo.getId());
            userActivityHomePage.setShareInviteButtonType(activityTaskInfo.getShareInviteButtonType());
            userActivityHomePage.setInviteButtonTips(activityTaskInfo.getInviteButtonTips());
            userActivityHomePage.setShareInviteButtonBackGroundImgUrl(activityTaskInfo.getShareInviteButtonBackGroundImgUrl());
        }
        //获取活力值
        UserActivityPointRanking userActivityPointRanking =
                userActivityPointRankingService.findByUserIdAndActivityId(currentUser.getId(), activityId);
        if (Objects.nonNull(userActivityPointRanking)) {
            userActivityHomePage.setRewardValue(userActivityPointRanking.getQuantity().intValue());
        }
        CompetitionUserInviteResponse competitionUserInvite = new CompetitionUserInviteResponse();
        competitionUserInvite.setInviteValue(userActivityHomePage.getRewardValue());
        competitionUserInviteService.matchRule(activityTaskInfo, activityId, competitionUserInvite);
        userActivityHomePage.setTips(competitionUserInvite.getTips());
        userActivityHomePage.setRate(competitionUserInvite.getRate());
        //获取该活动徽章信息
        List<MyBadgeRuleResponse> badgeRuleList = itemInfoService.findByActivityId(activityId,1);
        userActivityHomePage.setMyBadgeList(badgeRuleList);
        //如果用户已经报名、用户一定可能有一下信息，活力值、邀请人 是否满足徽章信息
        if (userActivityHomePage.getJoinActivity()) {
            //用户活力值是否拥有徽章信息
            List<MyBadgeRuleResponse> myBadgeList = userActivityHomePage.getMyBadgeList();
            if (CollectionUtils.isNotEmpty(myBadgeList)) {
                myBadgeList.stream().forEach(myBadgeRule -> {
                    RewardValue rewardValue = myBadgeRule.getRewardValue();
                    Integer myRewardValue = userActivityHomePage.getRewardValue();
                    if (Objects.nonNull(rewardValue) && rewardValue.compareValue(myRewardValue)) {
                        myBadgeRule.setLock(Boolean.TRUE);
                    }
                });
            }
        }
        return userActivityHomePage;
    }

    public List<MyBadgeRuleResponse> userBadgeList(UserPO currentUser, String activityId) {
       //获取活力值
        Integer point = 0;
        UserActivityPointRanking userActivityPointRanking =
                userActivityPointRankingService.findByUserIdAndActivityId(currentUser.getId(), activityId);
        if (Objects.nonNull(userActivityPointRanking)) {
            point = userActivityPointRanking.getQuantity().intValue();
        }
        final String rewardAlis = "活力值";
        //获取该活动徽章信息
        List<MyBadgeRuleResponse> badgeRuleList = itemInfoService.findByActivityId(activityId,0);
        Integer finalPoint = point;
        badgeRuleList.stream().forEach(myBadgeRule -> {
            RewardValue rewardValue = myBadgeRule.getRewardValue();
            if (Objects.nonNull(rewardValue) && rewardValue.compareValue(finalPoint)) {
                myBadgeRule.setLock(Boolean.TRUE);
            }
            myBadgeRule.setTips(rewardValue.rewardValueTips(rewardAlis));
        });
        return badgeRuleList;
    }

    public List<ActivityDetailResponse> detail(String appId) {
        List<ActivityPlatformConfig> list = activityPlatformConfigService.findByAppIdAndPlatform(appId, "qq");
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<String> activityIdList =
                list.stream().map(ActivityPlatformConfig::getActivityId).collect(Collectors.toList());
        List<ActivityInfo> activityInfoList =
                this.mongoTemplate.find(new Query().addCriteria(Criteria.where("id").in(activityIdList)),
                        ActivityInfo.class);
        return activityInfoList.stream().map(activityInfo -> {
            ActivityDetailResponse activityDetailResponse = new ActivityDetailResponse();
            activityDetailResponse.setActivityId(activityInfo.getId());
            activityDetailResponse.setActivityName(activityInfo.getName());
            activityDetailResponse.setImageUrl(activityInfo.getImageUrl());
            activityDetailResponse.setTags(activityInfo.getTags());
            activityDetailResponse.setSort(activityInfo.getPriority());
            activityDetailResponse.setActivityType(activityInfo.getType());
            return activityDetailResponse;
        }).collect(Collectors.toList()).stream().sorted(Comparator.comparing(ActivityDetailResponse::getSort).reversed()).collect(Collectors.toList());
    }

    public UserCompetitionQa findQaDetailActivityId(String activityId) {
       ActivityQaInfo activityQaInfo = activityQaInfoService.findByActivityIdAndQaNumber(activityId,4);
        if (Objects.isNull(activityQaInfo)) {
            throw new BusinessException("该活动未配置每日挑战题库");
        }
        UserCompetitionQa userCompetitionQa = new UserCompetitionQa();
        userCompetitionQa.setQaInfoId(activityQaInfo.getId());
        userCompetitionQa.setActivityId(activityQaInfo.getActivityId());
        userCompetitionQa.setQaDetail(activityQaInfo.getDetail());
        return userCompetitionQa;
    }

    /**
     * 获取邀请进度
     *
     * @param currentUser
     * @param activityId
     * @param type type 1 费竞赛累 2、竞赛类
     * @return
     */
    public UserActivityHomePageResponse getInviteProgress(UserPO currentUser,Integer type, String activityId) {
        UserActivityHomePageResponse userActivityHomePage = new UserActivityHomePageResponse();
        //获取任务信息
        ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.INVITE);
        if (Objects.nonNull(activityTaskInfo)) {
            userActivityHomePage.setInviteValue(activityTaskInfo.getPoints().intValue());
        }
        Integer rewardValue =0;
        if(type==1){
            UserActivityPointRanking userActivityPointRanking =
                    userActivityPointRankingService.findByUserIdAndActivityId(currentUser.getId(), activityId);
            if (Objects.nonNull(userActivityPointRanking)) {
                 rewardValue = userActivityPointRanking.getQuantity().intValue();
            }
        }else{
            rewardValue = userInviteRecordService.getInviteUserCount(currentUser.getId(),activityId,
                    activityTaskInfo.getId(), Boolean.TRUE).intValue();
        }
        userActivityHomePage.setRewardValue(rewardValue);
        //获取活力值

        CompetitionUserInviteResponse competitionUserInvite = new CompetitionUserInviteResponse();
        competitionUserInvite.setInviteValue(userActivityHomePage.getRewardValue());
        competitionUserInviteService.matchRule(activityTaskInfo, activityId, competitionUserInvite);
        if("invited-num-and-point".equals(activityTaskInfo.getProgressBarType())){
            userActivityHomePage.setTips(competitionUserInvite.getInvitedNumTips());
        }else{
            userActivityHomePage.setTips(competitionUserInvite.getTips());
        }
        userActivityHomePage.setCaLevel(competitionUserInvite.getCaLevel());
        userActivityHomePage.setInvitedNumTips(competitionUserInvite.getInvitedNumTips());
        userActivityHomePage.setRate(competitionUserInvite.getRate());
        if(type==2){
            userActivityHomePage.setInviteCount(rewardValue.longValue());
            userActivityHomePage.setShareInviteButtonType(activityTaskInfo.getShareInviteButtonType());
            userActivityHomePage.setInviteButtonTips(activityTaskInfo.getInviteButtonTips());
            userActivityHomePage.setShareInviteButtonBackGroundImgUrl(activityTaskInfo.getShareInviteButtonBackGroundImgUrl());
            userActivityHomePage.setInviteLevelDetail(activityTaskInfo.getDetail());
            userActivityHomePage.setInviteBackGroundImageUrl(activityTaskInfo.getInviteBackGroundImageUrl());
        }
        userActivityHomePage.setInviteValue(activityTaskInfo.getRatio().intValue());
        userActivityHomePage.setTaskId(activityTaskInfo.getId());
        return userActivityHomePage;
    }

    /**
     * 获取任务详情
     *
     * @param activityId
     * @param taskBizType
     * @return
     */
    public ActivityTaskInfo getTaskDetail(String activityId, TaskBizType taskBizType) {
        if (StringUtils.isBlank(activityId) || Objects.isNull(taskBizType)) {
            log.error(":>>> 活动任务不存在:{},taskBizeType:{}", activityId, taskBizType);
            throw new BusinessException("活动任务不存在");
        }
        Query query =
                new Query().addCriteria(Criteria.where("activityId").is(activityId).and("taskBizType").is(taskBizType));
        return mongoTemplate.findOne(query, ActivityTaskInfo.class);

    }

    /**
     * 获取纸质版证书领取信息
     *
     * @param req
     * @return
     */
    public UserCaDomain getUserCaInfo(@NotNull UserCaQuery req) {
        log.info(":>>> 开始获取纸质版证书信:{}", JSON.toJSON(req));
        UserCaDomain userCaDomain = new UserCaDomain();
        UserAddressInfo userAddressInfo = userAddressInfoService.findByUserId(req.getUserId());
        if (Objects.nonNull(userAddressInfo)) {
            BeanUtils.copyProperties(userAddressInfo, userCaDomain);
            userCaDomain.setUserAddressInfoId(userAddressInfo.getUserId());
        }
        UserInfoExtend extend = userInfoExtendService.findByUserIdAndAppId(req.getCurrentUser());
        if (Objects.nonNull(extend)) {
            userCaDomain.setName(extend.getName());
            userCaDomain.setMobile(extend.getMobile());
            userCaDomain.setUniversityId(extend.getUniversityId());
            userCaDomain.setUniversityName(extend.getUniversityName());
        }
        Query queryGroup = new Query().addCriteria(Criteria.where("activityId").is(req.getActivityId()).and(
                "taskBizType").is(req.getCaType()));
        CaGroupInfo groupInfo = mongoTemplate.findOne(queryGroup, CaGroupInfo.class);
        if (Objects.isNull(groupInfo)) {
            throw new BusinessException("未配置证书序列");
        }
        Query queryCa = new Query().addCriteria(Criteria.where("activityId").is(req.getActivityId()).and(
                "caGroupInfoId").is(groupInfo.getId()));
        List<CaInfo> caInfoList = mongoTemplate.find(queryCa, CaInfo.class);
        if (CollectionUtils.isEmpty(caInfoList)) {
            throw new BusinessException("未配置证书序列等级");
        }
        Optional<CaInfo> caInfoOptional =
                caInfoList.stream().filter(caInfo -> caInfo.getLevel().equals(req.getCaLevel())).findFirst();
        if (caInfoOptional.isPresent()) {
            userCaDomain.setCaInfo(caInfoOptional.get());
        }
        return userCaDomain;
    }

    public OrderInfo placeOrderByPoint(PointPlaceOrderVO req, UserPO userPO) {
        log.info(":>>> 开始积分下单:{},{}", JSON.toJSONString(req), JSON.toJSON(userPO));
        final String userId = userPO.getId();
        req.setOpenId(userPO.getOpenId());
        if (Objects.isNull(req) || StringUtils.isBlank(req.getCaInfoId()) || Objects.isNull(req.getUserAddressInfo())) {
            log.error(":>>> 用户下单参数错误:用户证书、地址信息为空");
            throw new BusinessException("用户积分下单参数错误");
        }
        ActivityInfo activityInfo = activityService.findOne(req.getActivityId());
        Integer requirePoint =0;
        //竞赛类型
        if(req.getActivityType()==2){
            UserActivityPointRanking userActivityPointRanking = userActivityPointRankingService.findByUserIdAndActivityId(userId, req.getActivityId());
            if (Objects.isNull(userActivityPointRanking)||userActivityPointRanking.getQuantity().intValue()==0){
                throw new BusinessException("对不起,挑战者不足,不能参与此次领取");
            }
            CertificateReceiveLimit certificateReceiveLimit = activityInfo.getCertificateReceiveLimit();
            requirePoint = certificateReceiveLimit.getPaperCertificateValue();
            if(Objects.isNull(certificateReceiveLimit)||userActivityPointRanking.getQuantity().intValue()<certificateReceiveLimit.getPaperCertificateValue()){
                throw new BusinessException("对不起,挑战者不足,不能参与此次领取");
            }
        }else{
            requirePoint = activityPointConfigService.getPoint(req.getActivityId(), "recieve-paper-ca");
            boolean hasPoint = userActivityPointRankingService.hasPoint(userPO.getId(), req.getActivityId(), "recieve" +
                    "-paper-ca");
            if (!hasPoint) {
                log.info(":>>> 用户:{} 积分不足", userPO.getId());
                throw new BusinessException("用户积分不足");
            }
        }

        boolean checkAddress = userAddressInfoService.checkUserAddress(req.getUserAddressInfo());
        if (!checkAddress) {
            log.info(":>>> 用户地址错误");
            throw new BusinessException("用户地址错误");
        }
        if (StringUtils.isBlank(req.getUserAddressInfo().getId())) {
            userAddressInfoService.create(req.getUserAddressInfo());
        } else {
            userAddressInfoService.update(req.getUserAddressInfo());
        }

        String orderNo = super.generateOrderNo("证书");
        log.info(":>>> 生成的证书订单编号:{}", orderNo);
        if (super.resubmit(3L, userPO.getId(), orderNo)) {
            log.info(":>>> 有已经待支付的订单,请不要重复支付");
            throw new BusinessException("请勿重复发起支付~");
        }
        Date date = new Date();
        OrderInfo orderInfo = new OrderInfo();
        try {
            orderInfo.setPlatform(req.getPlatform());
            orderInfo.setAppId(req.getAppId());
            orderInfo.setOpenId(req.getOpenId());
            orderInfo.setName(req.getUserAddressInfo().getRecieveName());
            orderInfo.setCaPrintName(req.getUserAddressInfo().getName());
            orderInfo.setMobile(req.getUserAddressInfo().getRecieveMobile());
            orderInfo.setProvince(req.getUserAddressInfo().getProvince());
            orderInfo.setCity(req.getUserAddressInfo().getCity());
            orderInfo.setArea(req.getUserAddressInfo().getArea());
            orderInfo.setAddress(req.getUserAddressInfo().getFullAddress());
            orderInfo.setUniversityId(req.getUniversityId());
            orderInfo.setCreatedTime(date);
            //  积分支付
            orderInfo.setMoneyType("3");
        } catch (Exception e) {
            throw new BusinessException("用户未报名活动");
        }
        if (StringUtils.isNotBlank(orderInfo.getUniversityId())) {
            Query queryU = new Query().addCriteria(Criteria.where("id").is(orderInfo.getUniversityId()));
            UniversityInfo universityInfo = mongoTemplate.findOne(queryU, UniversityInfo.class);
            if (Objects.nonNull(universityInfo)) {
                orderInfo.setUniversityName(universityInfo.getName());
            }
        }
        orderInfo.setOrderNo(orderNo);
        orderInfo.setCreatedTime(date);
        orderInfo.setStatus("1");
        orderInfo.setActivityId(req.getActivityId());
        orderInfo.setPayTime(date);
        orderInfo.setPayStatus("1");
        Integer price = 0;
        Integer num = 0;
        Integer totalPrice = 0;
        Integer expressFee = 0;
        Integer discountPrice = 0;
        String expressTips = "";
        PayConfigPage payConfig = activityPayConfigService.findByActivityId(req.getActivityId(), 0);
        PostageTemplate postageTemplate = null;
        if (Objects.nonNull(payConfig) && StringUtils.isNotBlank(payConfig.getPostageTemplateId())) {
            postageTemplate = postageTemplateService.findOne(payConfig.getPostageTemplateId());

        }
        CertificateActivityConfig certificateActivityConfig =
                certificateActivityConfigService.findByActivityIdAndBizType(activityInfo.getId(), req.getCaType());
        CaInfo ca = caInfoService.findCaInfoById(req.getCaInfoId());
        List<CaInfo> caInfos = new ArrayList<>();
        caInfos.add(ca);
        if (CollectionUtils.isEmpty(caInfos)) {
            log.error(":>>> 活动没有配置证书:{}", req.getActivityId());
            throw new BusinessException("活动没有配置证书");
        }
        String tips = "";
        for (CaInfo caInfo : caInfos) {
            String oorderNo = super.generateOrderNo("证书子订单");
            OOrderInfo oOrderInfo = buildOOrderInfo(caInfo, userPO, req.getActivityId(), orderNo, oorderNo, false);
            discountPrice = discountPrice + (caInfo.getOriginalPrice() == null ? caInfo.getPrice() :
                    caInfo.getOriginalPrice() - caInfo.getPrice());
            orderInfo.setTitle(caInfo.getName());
            oOrderInfo.setStatus("1");
            //  积分支付
            oOrderInfo.setMoneyType("3");
            if (ArrayUtils.isEmpty(caInfo.getCertificateImages())) {
                orderInfo.setImageUrl(caInfo.getCertificateImage());
            } else {
                orderInfo.setImageUrl(caInfo.getCertificateImages()[0]);
            }
            if(StringUtils.isNotBlank(caInfo.getInStockTips())){
                orderInfo.setTips(caInfo.getInStockTips());
                oOrderInfo.setTips(caInfo.getInStockTips());
                tips= caInfo.getInStockTips();
            }
            orderInfo.setGift(caInfo.getGift());
            price = price + caInfo.getPrice();
            HashMap<String, Integer> ee = postageTemplateService.getOrderExpreeFee(postageTemplate,
                    orderInfo.getProvince(), caInfo.getExpressFee());
            Integer e = ee.get("fee");
            Integer extraFee = ee.get("extraFee");
            orderInfo.setExtraExpressFee(extraFee);
//            totalPrice = totalPrice + caInfo.getPrice() + e + extraFee;
            expressFee = expressFee + e;
            num = num + 1;
            oOrderInfo.setSalePrice(requirePoint);
            oOrderInfo.setPayPrice(requirePoint / caInfos.size());
            //生成证书编号
            CaCollectReq caCollectReq = new CaCollectReq();
            caCollectReq.setCurrentUser(userPO);
            caCollectReq.setCaLevel(req.getCaLevel());
            caCollectReq.setTaskBizType(req.getCaType());
            caCollectReq.setCaType("2");
            caCollectReq.setActivityId(activityInfo.getId());
            caCollectReq.setCaGroupId(caInfo.getCaGroupInfoId());
            caCollectReq.setEdition(caInfo.getEdition());
            String certificateNo = caCollectService.buildCertificateNo(caCollectReq,
                    certificateActivityConfig.getLetterStart());
            oOrderInfo.setCertificateNo(certificateNo);
            mongoTemplate.insert(oOrderInfo);
            log.info(":>>> 证书:{} 邮费提示语:{}", caInfo.getId(), caInfo.getExpressFeeTips());
            if (StringUtils.isNotBlank(caInfo.getExpressFeeTips())) {
                expressTips = caInfo.getExpressFeeTips();
            }
            if (Objects.nonNull(caInfo.getGiftItems()) && !org.springframework.util.CollectionUtils.isEmpty(caInfo.getGiftItems())) {
                for (GiftCaInfo c : caInfo.getGiftItems()) {
                    String ooorderNo = super.generateOrderNo("证书子订单");
                    CaInfo gift=new CaInfo();
                    BeanUtils.copyProperties(c,gift);
                    OOrderInfo ooOrderInfo = buildOOrderInfo(gift, userPO, req.getActivityId(), orderNo, ooorderNo,
                            true);
                    ooOrderInfo.setStatus("1");
                    oOrderInfo.setMoneyType("3");
                    oOrderInfo.setPayPrice(0);
                    mongoTemplate.insert(ooOrderInfo);
                }
            }
        }
        orderInfo.setTotalFee(requirePoint);
        orderInfo.setItemPrice(requirePoint);
        orderInfo.setNum(num);
        orderInfo.setExpressFee(expressFee);
        orderInfo.setDiscountFee(discountPrice);
        orderInfo.setAccountInfoId(userPO.getId());
        if(StringUtils.isNotBlank(tips)){
            orderInfo.setTips(tips);
        }else{
            orderInfo.setTips(activityInfo.getOrderTips());
        }

        orderInfo.setCreatedTime(new Date());
        orderInfo.setExpressDesc(postageTemplate.getExpressDesc());
        if (StringUtils.isNotBlank(expressTips)) {
            orderInfo.setExpressFeeTips(expressTips);
        } else {
            orderInfo.setExpressFeeTips(postageTemplate.getExpressFeeTips());
        }
        UserInfoExtend userInfoExtend = userInfoExtendService.findByUserId(userPO.getId());
        if (Objects.nonNull(userInfoExtend)) {
            orderInfo.setSignUpMobile(userInfoExtend.getMobile());
            orderInfo.setSignUpName(userInfoExtend.getName());
            orderInfo.setUniversityId(userInfoExtend.getUniversityId());
            orderInfo.setUniversityName(userInfoExtend.getUniversityName());
            orderInfo.setMobile(userInfoExtend.getMobile());
        }

        orderInfo = mongoTemplate.insert(orderInfo);
        log.info(":>>> 订单:{},邮费提示语:{},证书配置提示语:{}", orderInfo.getOrderNo(), orderInfo.getExpressFeeTips(), expressTips);
        if(req.getActivityType()!=1&&req.getActivityType()!=2){
            //扣减用户积分
            UserPointsDetail userPointsDetail = new UserPointsDetail();
            userPointsDetail.setUserId(userPO.getId());
            userPointsDetail.setOptDate(new Date());
            userPointsDetail.setAction("sub");
            userPointsDetail.setBizType("ca-receive-paper");
            userPointsDetail.setBizDesc("兑换纸质证书");
            userPointsDetail.setComments("兑换纸质证书");
            userPointsDetail.setPoints(requirePoint);
            userPointsDetail.setPlatform(userPO.getCurrentPlatform());
            userPointsService.subPoint(userPointsDetail);
            UserActivityPointDetail detail = new UserActivityPointDetail();
            detail.setActivityId(req.getActivityId());
            detail.setUserId(req.getUserId());
            detail.setUserPO(userPO);
            detail.setPoints(requirePoint);
            detail.setAction("sub");
            detail.setBizDesc("领取纸质版证书");
            detail.setBizType("ca-receive-paper");
            userActivityPointDetailService.create(detail);
            userActivityPointRankingService.subPoint(userId, req.getActivityId(), requirePoint);
        }
        UserCaReceiveRecord userCaReceiveRecord = new UserCaReceiveRecord();
        userCaReceiveRecord.setActivityId(req.getActivityId());
        userCaReceiveRecord.setCaLevel(req.getCaLevel());
        userCaReceiveRecord.setCaType(req.getCaType());
        userCaReceiveRecord.setMaterial(CaMaterialType.PAPER);
        userCaReceiveRecord.setMoneyType("3");
        userCaReceiveRecord.setReceived(true);
        userCaReceiveRecord.setReceiveTime(new Date());
//        userCaReceiveRecord.setUserCaId(userCa.getId());
        userCaReceiveRecord.setComments("积分领取纸质版");
        userCaReceiveRecord.setPrice(requirePoint);
        userCaReceiveRecord.setUserId(userId);
        userCaReceiveRecordService.create(userCaReceiveRecord);
        return orderInfo;
    }

    private OOrderInfo buildOOrderInfo(CaInfo caInfo, UserPO userPO,
                                       String activityId, String orderNo,
                                       String oorderNo, boolean gift) {
        OOrderInfo oOrderInfo = new OOrderInfo();
        oOrderInfo.setOrderNo(orderNo);
        oOrderInfo.setOOrderNo(oorderNo);
        oOrderInfo.setCreatedTime(new Date());
        oOrderInfo.setAccountInfoId(userPO.getId());
        if (ArrayUtils.isEmpty(caInfo.getCertificateImages())) {
            oOrderInfo.setImageUrl(caInfo.getCertificateImage());
        } else {
            oOrderInfo.setImageUrl(caInfo.getCertificateImages()[0]);
        }

        oOrderInfo.setCaInfo(caInfo);
        oOrderInfo.setItemType("ca");
        oOrderInfo.setItemInfoId(caInfo.getId());
        oOrderInfo.setStatus("0");
        oOrderInfo.setItemTitle(caInfo.getName());
        if (ArrayUtils.isEmpty(caInfo.getCertificateImages())) {
            oOrderInfo.setItemImageUrl(caInfo.getCertificateImage());
        } else {
            oOrderInfo.setItemImageUrl(caInfo.getCertificateImages()[0]);
        }
        oOrderInfo.setSalePrice(caInfo.getPrice());
        oOrderInfo.setItemPrice(caInfo.getOriginalPrice());
        oOrderInfo.setAppId(userPO.getAppId());
        oOrderInfo.setOpenId(userPO.getOpenId());
        oOrderInfo.setExpressFee(caInfo.getExpressFee().toString());
        oOrderInfo.setPlatform("wechat-h5");
        oOrderInfo.setCaGift(caInfo.getCaGift());
        oOrderInfo.setNum(1);
        oOrderInfo.setOpenId(userPO.getOpenId());
        oOrderInfo.setActivityId(activityId);
        oOrderInfo.setGift(caInfo.getGift());
        if (gift) {
            oOrderInfo.setGifted(true);
            oOrderInfo.setSalePrice(0);
            oOrderInfo.setItemPrice(0);
            oOrderInfo.setSalePriceBack(caInfo.getPrice());
            oOrderInfo.setItemPriceBack(caInfo.getOriginalPrice());
            oOrderInfo.setItemPrice(0);
        } else {
            oOrderInfo.setGifted(false);
        }
        return oOrderInfo;
    }
}
